using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Domain.Entities.Auditing;

namespace MatrixFramework.Shared.Domain.Users
{
    /// <summary>
    /// Matrix Framework应用角色
    /// 继承ABP Identity角色，扩展企业级功能
    /// </summary>
    public class AppRole : IdentityRole, IMultiTenant, IFullAuditedObject
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public Guid? TenantId { get; set; }

        #region 基础信息

        /// <summary>
        /// 角色代码
        /// </summary>
        [Required]
        [StringLength(64)]
        public string Code { get; set; }

        /// <summary>
        /// 角色类型
        /// </summary>
        public RoleType RoleType { get; set; } = RoleType.Custom;

        /// <summary>
        /// 角色级别
        /// </summary>
        public int Level { get; set; } = 0;

        /// <summary>
        /// 父角色ID（用于角色继承）
        /// </summary>
        public Guid? ParentRoleId { get; set; }

        /// <summary>
        /// 排序顺序
        /// </summary>
        public int SortOrder { get; set; } = 0;

        /// <summary>
        /// 角色图标
        /// </summary>
        [StringLength(64)]
        public string Icon { get; set; }

        /// <summary>
        /// 角色颜色
        /// </summary>
        [StringLength(16)]
        public string Color { get; set; }

        /// <summary>
        /// 是否为系统角色
        /// </summary>
        public bool IsSystem { get; set; } = false;

        /// <summary>
        /// 是否为默认角色
        /// </summary>
        public bool IsDefault { get; set; } = false;

        #endregion

        #region 权限和安全

        /// <summary>
        /// 角色权限列表
        /// </summary>
        public virtual List<RolePermission> Permissions { get; protected set; } = new();

        /// <summary>
        /// 数据权限范围
        /// </summary>
        public DataPermissionScope DataScope { get; set; } = DataPermissionScope.All;

        /// <summary>
        /// 自定义数据权限范围部门ID列表
        /// </summary>
        public virtual List<RoleDataPermissionDepartment> DataPermissionDepartments { get; protected set; } = new();

        /// <summary>
        /// 是否启用数据权限
        /// </summary>
        public bool EnableDataPermission { get; set; } = false;

        /// <summary>
        /// 最大会话数
        /// </summary>
        public int MaxSessionCount { get; set; } = -1; // -1表示无限制

        /// <summary>
        /// 会话超时时间（分钟）
        /// </summary>
        public int SessionTimeoutMinutes { get; set; } = 480; // 默认8小时

        /// <summary>
        /// IP地址限制
        /// </summary>
        [StringLength(1024)]
        public string IpRestrictions { get; set; }

        /// <summary>
        /// 时间限制（JSON格式）
        /// </summary>
        [StringLength(2048)]
        public string TimeRestrictions { get; set; }

        #endregion

        #region Keycloak集成

        /// <summary>
        /// Keycloak角色名称
        /// </summary>
        [StringLength(128)]
        public string KeycloakRoleName { get; set; }

        /// <summary>
        /// Keycloak客户端ID列表
        /// </summary>
        public virtual List<RoleClientMapping> ClientMappings { get; protected set; } = new();

        /// <summary>
        /// 最后一次Keycloak同步时间
        /// </summary>
        public DateTime? LastKeycloakSyncTime { get; set; }

        /// <summary>
        /// 是否启用Keycloak同步
        /// </summary>
        public bool EnableKeycloakSync { get; set; } = true;

        #endregion

        #region 审计字段

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreationTime { get; set; }

        /// <summary>
        /// 创建者ID
        /// </summary>
        public Guid? CreatorId { get; set; }

        /// <summary>
        /// 最后修改时间
        /// </summary>
        public DateTime? LastModificationTime { get; set; }

        /// <summary>
        /// 最后修改者ID
        /// </summary>
        public Guid? LastModifierId { get; set; }

        /// <summary>
        /// 是否已删除
        /// </summary>
        public bool IsDeleted { get; set; }

        /// <summary>
        /// 删除时间
        /// </summary>
        public DateTime? DeletionTime { get; set; }

        /// <summary>
        /// 删除者ID
        /// </summary>
        public Guid? DeleterId { get; set; }

        #endregion

        #region 业务方法

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="permissionName">权限名称</param>
        /// <param name="isGranted">是否授予</param>
        public void AddPermission(string permissionName, bool isGranted = true)
        {
            // 移除现有权限
            Permissions.RemoveAll(x => x.PermissionName == permissionName);

            // 添加新权限
            Permissions.Add(new RolePermission
            {
                PermissionName = permissionName,
                IsGranted = isGranted,
                GrantedAt = DateTime.UtcNow
            });
        }

        /// <summary>
        /// 移除权限
        /// </summary>
        /// <param name="permissionName">权限名称</param>
        public void RemovePermission(string permissionName)
        {
            Permissions.RemoveAll(x => x.PermissionName == permissionName);
        }

        /// <summary>
        /// 检查是否有指定权限
        /// </summary>
        /// <param name="permissionName">权限名称</param>
        /// <returns>是否有权限</returns>
        public bool HasPermission(string permissionName)
        {
            var permission = Permissions.Find(x => x.PermissionName == permissionName);
            return permission?.IsGranted ?? false;
        }

        /// <summary>
        /// 批量添加权限
        /// </summary>
        /// <param name="permissions">权限列表</param>
        public void AddPermissions(List<string> permissions)
        {
            foreach (var permissionName in permissions)
            {
                AddPermission(permissionName, true);
            }
        }

        /// <summary>
        /// 设置数据权限范围
        /// </summary>
        /// <param name="dataScope">数据权限范围</param>
        /// <param name="departmentIds">部门ID列表（当数据权限为自定义部门时使用）</param>
        public void SetDataPermissionScope(DataPermissionScope dataScope, List<Guid> departmentIds = null)
        {
            DataScope = dataScope;
            EnableDataPermission = true;

            // 清除现有部门权限
            DataPermissionDepartments.Clear();

            // 添加新的部门权限
            if (dataScope == DataPermissionScope.CustomDepartments && departmentIds?.Any() == true)
            {
                foreach (var departmentId in departmentIds)
                {
                    DataPermissionDepartments.Add(new RoleDataPermissionDepartment
                    {
                        DepartmentId = departmentId,
                        GrantedAt = DateTime.UtcNow
                    });
                }
            }
        }

        /// <summary>
        /// 添加客户端映射
        /// </summary>
        /// <param name="clientId">客户端ID</param>
        /// <param name="clientRoleName">客户端角色名称</param>
        public void AddClientMapping(string clientId, string clientRoleName)
        {
            // 移除现有映射
            ClientMappings.RemoveAll(x => x.ClientId == clientId);

            // 添加新映射
            ClientMappings.Add(new RoleClientMapping
            {
                ClientId = clientId,
                ClientRoleName = clientRoleName,
                MappedAt = DateTime.UtcNow
            });
        }

        /// <summary>
        /// 移除客户端映射
        /// </summary>
        /// <param name="clientId">客户端ID</param>
        public void RemoveClientMapping(string clientId)
        {
            ClientMappings.RemoveAll(x => x.ClientId == clientId);
        }

        /// <summary>
        /// 更新Keycloak信息
        /// </summary>
        /// <param name="keycloakRoleName">Keycloak角色名称</param>
        public void UpdateKeycloakInfo(string keycloakRoleName)
        {
            KeycloakRoleName = keycloakRoleName;
            LastKeycloakSyncTime = DateTime.UtcNow;
        }

        /// <summary>
        /// 检查IP地址是否允许访问
        /// </summary>
        /// <param name="ipAddress">IP地址</param>
        /// <returns>是否允许访问</returns>
        public bool IsIpAddressAllowed(string ipAddress)
        {
            if (string.IsNullOrEmpty(IpRestrictions))
            {
                return true; // 无限制
            }

            var allowedIps = IpRestrictions.Split(',', StringSplitOptions.RemoveEmptyEntries);
            return allowedIps.Contains(ipAddress.Trim());
        }

        /// <summary>
        /// 检查当前时间是否允许访问
        /// </summary>
        /// <param name="currentTime">当前时间</param>
        /// <returns>是否允许访问</returns>
        public bool IsTimeAllowed(DateTime currentTime)
        {
            if (string.IsNullOrEmpty(TimeRestrictions))
            {
                return true; // 无限制
            }

            // 这里应该解析TimeRestrictions JSON并检查时间范围
            // 简化实现，返回true
            return true;
        }

        /// <summary>
        /// 获取角色层级路径
        /// </summary>
        /// <returns>角色层级路径</returns>
        public string GetHierarchyPath()
        {
            var path = new List<string> { Code };
            // 这里应该递归获取父角色的路径
            // 简化实现，只返回当前角色代码
            return string.Join(" > ", path);
        }

        #endregion

        protected AppRole()
        {
        }

        public AppRole(
            Guid id,
            string name,
            string displayName = null) : base(id, name, displayName)
        {
            CreationTime = DateTime.UtcNow;
            Code = name;
            RoleType = RoleType.Custom;
        }

        public AppRole(
            Guid id,
            string name,
            string code,
            string displayName = null,
            RoleType roleType = RoleType.Custom) : base(id, name, displayName)
        {
            CreationTime = DateTime.UtcNow;
            Code = code;
            RoleType = roleType;
        }
    }

    /// <summary>
    /// 角色类型枚举
    /// </summary>
    public enum RoleType
    {
        /// <summary>
        /// 系统角色
        /// </summary>
        System = 0,

        /// <summary>
        /// 内置角色
        /// </summary>
        BuiltIn = 1,

        /// <summary>
        /// 自定义角色
        /// </summary>
        Custom = 2,

        /// <summary>
        /// 临时角色
        /// </summary>
        Temporary = 3
    }

    /// <summary>
    /// 数据权限范围枚举
    /// </summary>
    public enum DataPermissionScope
    {
        /// <summary>
        /// 全部数据
        /// </summary>
        All = 0,

        /// <summary>
        /// 本部门数据
        /// </summary>
        Department = 1,

        /// <summary>
        /// 本部门及子部门数据
        /// </summary>
        DepartmentAndSub = 2,

        /// <summary>
        /// 仅本人数据
        /// </summary>
        Self = 3,

        /// <summary>
        /// 自定义部门数据
        /// </summary>
        CustomDepartments = 4,

        /// <summary>
        /// 无数据权限
        /// </summary>
        None = 5
    }
}